/*
 * Copyright (C) 2005 Johan Maasing johan at zoom.nu Licensed under the Apache
 * License, Version 2.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
 * or agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
package nu.zoom.swing.desktop.plugin.portunis.impl;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.security.Key;
import java.security.cert.Certificate;
import java.util.ArrayList;
import java.util.HashMap;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;

import javax.swing.JScrollPane;
import nu.zoom.swing.desktop.Workbench;
import nu.zoom.swing.desktop.plugin.portunis.Utils;
import nu.zoom.swing.desktop.plugin.portunis.ZoomKeyStore;
import nu.zoom.swing.layout.VerticalPanel;

import org.ops4j.gaderian.Messages;

/**
 * A componentn that displays a list of key entries in a keystore. The user can
 * select a key alias to see information about the key.
 * 
 * @see nu.zoom.swing.desktop.plugin.portunis.impl.KeyComponentFactory
 * @author $Author: johan $
 * @version $Revision: 1.1 $
 */
public class DisplayKeys extends JComponent {

    private static final long serialVersionUID = -1;
    private final HashMap keyPasswords = new HashMap();
    private Component currentKey = null;
    private final Messages messages;
    private final Workbench workbench;
    private final KeyComponentFactory keyComponentFactory;
    private final ZoomKeyStore store;
    private final CertificateComponentFactory certComponentFactory;

    public DisplayKeys(final Workbench workbench, final ZoomKeyStore store,
            final ArrayList<String> keyAliases, final Messages messages) {
        super();
        this.messages = messages;
        this.workbench = workbench;
        this.store = store;
        keyComponentFactory = new KeyComponentFactory(messages);
        certComponentFactory = new CertificateComponentFactory(workbench,
                messages);
        Box keyButtonBox = Box.createVerticalBox();
        for (String alias : keyAliases) {
            JButton aliasButton = new JButton(alias, Utils.getIconFromMessages(
                    messages, "keystore.display.key.icon"));
            final String finalAlias = alias;
            aliasButton.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    showKey(finalAlias);
                }
            });
            keyButtonBox.add(aliasButton);
        }
        setLayout(new BorderLayout());
        add(new JScrollPane(keyButtonBox), BorderLayout.WEST);
        currentKey = new JLabel(messages.getMessage("keystore.display.key.selectone"));
        add(currentKey, BorderLayout.CENTER);
    }

    private void showKey(String alias) {
        // Ask for password
        char[] password = (char[]) keyPasswords.get(alias);
        boolean done = false;
        do {
            if (password == null) {
                KeyPasswordDialog dlg = new KeyPasswordDialog(workbench,
                        messages);
                dlg.pack();
                dlg.setVisible(true);
                if (dlg.isCloseOK()) {
                    password = dlg.getPassword();
                } else {
                    password = null;
                    done = true;
                }
            }
            if (password != null) {
                try {
                    // get key
                    Key key = store.getKey(alias, password);
                    done = true;
                    remove(currentKey);
                    VerticalPanel keyPanel = new VerticalPanel();
                    JComponent keyComponent = keyComponentFactory.getKeyDescription(key);
                    keyPanel.addRow(keyComponent);
                    Certificate[] chain = store.getCertificateChain(alias);
                    if (chain != null) {
                        for (int i = 0; i < chain.length; i++) {
                            JComponent certcomponent = certComponentFactory.getCertificateComponent(chain[i]);
                            certcomponent.setBorder(BorderFactory.createTitledBorder(messages.getMessage("keystore.display.key.certtitle")));
                            keyPanel.addRow(certcomponent);
                        }
                    } else {
                        keyPanel.addRow(new JLabel(messages.getMessage("keystore.display.key.nocert")));
                    }
                    currentKey = keyPanel;
                    add(currentKey, BorderLayout.CENTER);
                    revalidate();
                } catch (Exception e) {
                    workbench.getErrorReporter().reportError(
                            messages.getMessage("keystore.display.key.notrecovered"),
                            e);
                    password = null;
                }
            }
        } while (!done);
    }
}
